extern "C" {
	#include <sapi/embed/php_embed.h>
}

#include <string>
#include <iostream>

using namespace std;

#ifdef ZTS
    void ***tsrm_ls;
#endif
/* Extension bits */
zend_module_entry php_mysql_module_entry = {
    STANDARD_MODULE_HEADER,
    "mysql", /* extension name */
    NULL, /* function entries */
    NULL, /* MINIT */
    NULL, /* MSHUTDOWN */
    NULL, /* RINIT */
    NULL, /* RSHUTDOWN */
    NULL, /* MINFO */
    "1.0", /* version */
    STANDARD_MODULE_PROPERTIES
};
/* Embedded bits */
static void startup_php(void)
{
    int argc = 1;
    char *argv[2] = { "embed5", NULL };
	php_embed_module.php_ini_path_override = "php.ini"; 
 //   php_embed_init(argc, argv PTSRMLS_CC);
	 php_embed_init(0, NULL);
 //   zend_startup_module(&php_mysql_module_entry);
}


/*
* key 10.1.48.58:10654->10.1.48.58:22456
* value json_string
*
*/
 int script_handler(string &key, string &value){
	zval z_funcname;  
	ZVAL_STRING(&z_funcname, "handler", 1);  
	  
	zval *zp_key;  
	MAKE_STD_ZVAL(zp_key);  
	ZVAL_STRING(zp_key, key.c_str(), 1);  
	  
	zval *zp_value;  
	MAKE_STD_ZVAL(zp_value);  
	ZVAL_STRING(zp_value, value.c_str(), 1);  
	  
	zval z_retval;  
	zval *z_params[] = {zp_key, zp_value};  
	int call_ret = call_user_function(EG(function_table), NULL, &z_funcname, &z_retval,
		sizeof(z_params) / sizeof(z_params[0]), z_params TSRMLS_CC);  
	
	int func_ret = Z_LVAL_P(&z_retval);  
	  
	zval_ptr_dtor(&zp_key);  
	zval_ptr_dtor(&zp_value);  
	zval_dtor(&z_funcname);  
	zval_dtor(&z_retval);  
	  
	if (call_ret < 0 || func_ret < 0) {  
	//    base->log_.LOG_P_PID(LOG_FATAL, "call_user_function fail. call_ret=%d func_ret=%d\n", call_ret, func_ret);  
		printf("call_user_function fail. call_ret=%d func_ret=%d\n", call_ret, func_ret);
	    return -1;  
	}  

	return 0;
}



static void execute_php(char *filename, string &key, string &value)
{
	printf("filename=%s\n", filename);
    zend_first_try {
        char *include_script;
        spprintf(&include_script, 0, "include '%s';", filename);
        zend_eval_string(include_script, NULL, filename TSRMLS_CC);
		script_handler(key, value);
        efree(include_script);
    } zend_end_try();
}




int main(int argc, char *argv[])
{
    if (argc <= 1) {
        printf("Usage: embed4 scriptfile");
        return -1;
    }
    startup_php();
	string key = "this is key";
	string value = "this is value";
    execute_php(argv[1], key, value);
    php_embed_shutdown(TSRMLS_CC);
    return 0;
}
